package com.zrf.tool;

import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import us.monoid.json.JSONArray;
import us.monoid.json.JSONObject;



public class Tools {

	//生成随机数
	private static Integer getID(){
		Integer id = 1000000000;
		return (int)(Math.random()*id);
	}
	
	//生成随机ID
	public static Integer getListID(List<?> list){
		Integer id = Tools.getID();
		if(list!=null){
			for (Integer integer : (List<Integer>)list) {
				if(id==integer){
					Tools.getListID(list);
				}
			}
			
		}
		return id;
	}
	
	//货币格式
	public static String moneyChange(Double num){
		try {
			
			NumberFormat nf = NumberFormat.getNumberInstance();
			nf.setMaximumFractionDigits(3);
			nf.setMinimumIntegerDigits(6);
			return nf.format(num);
		} catch (Exception e) {
			e.printStackTrace();
			// TODO: handle exception
		}
		return "0.0";
	}
	
	
	
	//json串
	public ArrayList<Map<String, String>> getDataFromJson(String json){
		ArrayList<Map<String, String>> data = new ArrayList<Map<String, String>>();
		
		try {
			JSONObject jsonObject = new JSONObject(json);
			Iterator<String> keys = jsonObject.keys();
			if(keys.hasNext()){
				String str1 = jsonObject.getString(keys.next());
				if(str1.indexOf("[")==0){
					JSONArray arr = new JSONArray(str1);
					for(int i=0;i<arr.length();i++){
						Map<String, String> jsonMap = new HashMap<String,String>();
						JSONObject temp = new JSONObject(arr.get(i).toString());
						Iterator<String> tempkeys = temp.keys();
						while(tempkeys.hasNext()){
							String key = tempkeys.next();
							jsonMap.put(key, temp.getString(key));
						}
						data.add(jsonMap);
					}
				}else{
					Map<String,String> jsonMap = new HashMap<String,String>();
                    JSONObject temp = new JSONObject(json);
                    Iterator<String> tempKeys = temp.keys();
                    while(tempKeys.hasNext()){
                        String key = tempKeys.next();
                        jsonMap.put(key,temp.getString(key));
                    }
                    data.add(jsonMap);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			// TODO: handle exception
		}
		
		return data;
	}
	
	
	
	
	
	
}
